package info.sybian.web.view;

import java.io.File;
import java.io.FileInputStream;
import java.util.concurrent.ConcurrentHashMap;

import objot.util.Bytes;

/**
 * LGPL V3
 * 
 * @author CrazyBird Modified by nkadun for auto-loading
 */
public class ViewEngine {
	private String pageDir;
	private ConcurrentHashMap<String, ViewTemplate> tems;
	private ConcurrentHashMap<String, Long> temTimes;

	public ViewEngine(String pageDir_) {
		pageDir = pageDir_;
		tems = new ConcurrentHashMap<String, ViewTemplate>(128, 0.8f, 32);
		temTimes = new ConcurrentHashMap<String, Long>(128, 0.8f, 32);
	}

	public ViewTemplate template(String file) throws Exception {
		ViewTemplate t = tems.get(file);
		File f = new File(pageDir, file);
		if(t == null || f.lastModified() > temTimes.get(file)) {
			Bytes bs = new Bytes(new FileInputStream(f), true);
			t = new ViewTemplate();
			t.init(this, bs.bytes, bs.beginBi, bs.end1Bi, null, 0, true);
			tems.put(file, t);
			temTimes.put(file, f.lastModified());
		}
		return t;
	}
}
